package org.simplextensions;

import java.io.IOException;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;

import org.simplextensions.configuration.BundleConfiguration;
import org.simplextensions.configuration.ConfigurationReader;
import org.simplextensions.registry.ExtensionRegistry;
import org.simplextensions.registry.ExtensionRegistryServiceAdapter;
import org.simplextensions.registry.IExtensionRegistry;
import org.simplextensions.registry.IServiceRegistry;

/**
 * @author Tomasz Krzyzak, <a
 *         href="mailto:tomasz.krzyzak@gmail.com">tomasz.krzyzak@gmail.com</a>
 * @since 2009-08-12 23:37:37
 * 
 */
public class Simplextensions {

	private Simplextensions() {
	}

	private static IExtensionRegistry defaultServiceRegistry;

	public static synchronized IExtensionRegistry getDefault() {
		if (defaultServiceRegistry == null) {
			try {
				defaultServiceRegistry = createExtensionRegistry(getBundleList());
			} catch (Exception e) {
				throw new RuntimeException(e);
			}
		}
		return defaultServiceRegistry;
	}

	public static List<BundleConfiguration> getBundleList() throws IOException {
		return ConfigurationReader.getBundleList();
	}

	public synchronized static IExtensionRegistry createNewRegistry() {
		try {
			return createExtensionRegistry(getBundleList());
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	public IExtensionRegistry createExtensionRegistry(BundleConfiguration... bundles) throws Exception {
		return createExtensionRegistry(Arrays.asList(bundles));
	}

	/**
	 * creates new instance of serviceRegistry, extensionRegistry and links them
	 * together (serviceregistry as extension of extensionregistry and
	 * extensionregistry as service of serviceregistry)
	 * 
	 * @return
	 * @throws Exception
	 */
	public static IExtensionRegistry createExtensionRegistry(Collection<BundleConfiguration> bundles) throws Exception {

		ExtensionRegistry extensionRegistry = new ExtensionRegistry(bundles);
		extensionRegistry.start();

		IServiceRegistry sr = extensionRegistry.getServiceRegistry();
		sr.start();

		sr.registerService(IExtensionRegistry.class, new ExtensionRegistryServiceAdapter(extensionRegistry));

		return extensionRegistry;
	}

}
